var useragent = require('useragent');
var validator = require('validator');
var moment = require('moment');
var CONFIG = require('../config/config').Config;
// var nodemailer = require('nodemailer');
var fs = require('fs-extra');
// var gm = require('gm');
var objectid = require('objectid');

var handler = module.exports;

exports.getClientIp = function (req) {
	if (req.headers['x-forwarded-for']) {
		return req.headers['x-forwarded-for'];
	}

	if (req.connection && req.connection.remoteAddress) {
		return req.connection.remoteAddress;
	}

	if (req.socket && req.socket.remoteAddress) {
		return req.socket.remoteAddress;
	}

	if (req.connection && req.connection.socket && req.connection.socket.remoteAddress) {
		return req.connection.socket.remoteAddress;
	}

	return '0.0.0.0'; // invalid IP
};

exports.errorHandle = function (status, msg) {
  return {
    status: status,
    error: msg
  };
};

// 获取字符长度
exports.getByteLen = function (val) {
  var len = 0;
  for (var i = 0; i < val.length; i++) {
    if (val[i].match(/[^x00-xff]/ig) != null) //全角
      len += 2;
    else
      len += 1;
  };
  return len;
};

exports.getUserAgent = function (req) {
  return useragent.parse(req.headers['user-agent'])
};

exports.getUa = function (req) {
  return useragent.is(req.headers['user-agent'])
};

exports.getClientIP = function (req) {
  var realip = req.headers['x-real-ip']; // using NGINX
  if (!realip) {
    realip = req.ip;
  }

  if (realip) {
    if (!(/^\d+\.\d+.\d+.\d+$/.test(realip))) {
      realip = '127.0.0.1';
    }
  } else {
    realip = '127.0.0.1';
  }

  return realip;
};

exports.isChina = function (s) {
  var patrn = /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/gi;

  if (!patrn.exec(s)) {
    return false;
  }

  return true;
};

exports.isDefined = function(x) {
  if ((x == null) || (typeof(x) == 'undefined')) {
    return false;
  }

  return true;
}

exports.cleanSex = function(sex) {
  if (sex != 'Male' && sex != 'Female') {
    return 'Unknown';
  }

  return sex;
};

exports.cleanString = function(str) {
  if (!handler.isDefined(str)) {
    return '';
  }

  return str;
};

exports.cleanRegexString = function(str) {
  if (!handler.isDefined(str)) {
    return '';
  }

  // ^ $ . * +  - ? = ! : | \ / ( ) [ ] { }
  return str.replace(/(\^|\$|\.|\*|\+|\-|\?|\=|\!|\:|\||\\|\/|\(|\)|\[|\]|\{|\})/g, '\\$1');
};

// 如果第二次参数不为null，则生成随机的纯数字串，否则生成随机的字符串。
exports.generateRandomAlphaNum = function(len, radix) {
    radix = radix ? 10 : 36;
    var rdmString = "";
    for (; rdmString.length < len; rdmString += Math.random().toString(radix).substr(2));
    return rdmString.substr(0, len);
}

exports.genRandFileName = function(suffix) {
  return moment().format("YYYY-MM-DD") + '-' + handler.generateRandomAlphaNum(7) + (suffix ?  ('-' + suffix) : '');
}

/**
* 删除左右两端的空格
*/
exports.trim = function(str) {
     return str.replace(/(^\s*)|(\s*$)/g, '');
};

/**
* 删除左边的空格
*/
exports.ltrim = function(str) {
     return str.replace(/(^\s*)/g, '');
};

/**
* 删除右边的空格
*/
exports.rtrim = function(str) {
     return str.replace(/(\s*$)/g, '');
};

exports.isStrEmpty = function(str){
  if (!handler.isDefined(str) || (str == '')) {
    return true;
  }

  return false;
}

exports.isTrimmedEmpty = function(str){
  if (!handler.isDefined(str) || (handler.trim(str) == '')) {
    return true;
  }

  return false;
}

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

exports.sendMail = function(mailto, subject, html) {
  // var smtpTransport = nodemailer.createTransport('SMTP', CONFIG.emailFrom);
  //   var mailOptions = {
  //       from: [CONFIG.emailFrom.name, CONFIG.emailFrom.auth.user].join(' '),
  //       to: mailto,
  //       subject: subject,
  //       html: html
  //   };

  //   smtpTransport.sendMail(mailOptions, function(error, response){
  //       if (error) {
  //           console.log(error);
  //       } else {
  //           console.log('Message sent: ' + response.message);
  //       }

  //       smtpTransport.close();
  //   });
};

exports.baseName = function(str) {
  var base = new String(str).substring(str.lastIndexOf('/') + 1);
  if(base.lastIndexOf(".") != -1)
      base = base.substring(0, base.lastIndexOf("."));
  return base;
}

exports.extName = function(str) {
  var base = new String(str).substring(str.lastIndexOf('/') + 1);
  if(base.lastIndexOf(".") != -1) {
    return base.substring(base.lastIndexOf("."));
  }
  return '';
}

exports.getFilesInfo = function(req, sources, destinations, destDir) {
  if (!req.files) {
    return;
  }

  var i = 0;

  for (var key in req.files) {
    if (i > CONFIG.max_upload_files) {
      break;
    }

    if (
      handler.isStrEmpty(req.files[key].originalFilename) ||
      (req.files[key].size <= 0)
      ) {
      continue;
    }

    var basename = handler.baseName(req.files[key].originalFilename);
    var extname = handler.extName(req.files[key].originalFilename);
    var filename = basename + ((extname != '') ? extname : '.jpg');

    sources[i] = req.files[key].path;
    destinations[i] = destDir + '/' + handler.genRandFileName(filename);
    i++;
  }
}

exports.moveFilesToDest = function(sources, destinations) {
  // for (var i = 0; i < sources.length; i++) {
  //   (function() {
  //     var dest = './public' + destinations[i];
  //     var thumb100 = dest.replace(/(.+\/)/, "$1100_");
  //     var thumb200 = dest.replace(/(.+\/)/, "$1200_");
  //     var thumb800 = dest.replace(/(.+\/)/, "$1800_");

  //     fs.move(sources[i], dest, function (err) {
  //       if (err) {
  //         console.log(err);
  //       } else {
  //         gm(dest).quality(50).resize(100).noProfile().write(thumb100, function(err){
  //           err && console.log('gm error: ' + err);
  //         });
  //         gm(dest).quality(50).resize(200).noProfile().write(thumb200, function(err){});
  //         gm(dest).quality(50).resize(800).noProfile().write(thumb800, function(err){});
  //       }
  //     });
  //   })();
  // }
}

String.prototype.htmlEscape = function() {
    return String(this)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/\n/g, '<br/>');
}

String.prototype.htmlUnescape = function(){
    return String(this)
        .replace(/&quot;/g, '"')
        .replace(/&#39;/g, "'")
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&amp;/g, '&');
}

String.prototype.refineAvatar = function() {
  if (this != '') {
    return this.replace(/(.+\/)/, "$1100_");
  }

  return "/assets/avatars/avatar.png";
}

String.prototype.refineAvatarBig = function() {
  if (this != '') {
    return this.replace(/(.+\/)/, "$1200_");
  }

  return "/assets/avatars/avatar.png";
}

exports.randomAvatar = function() {
  var avatars = [
    'avatar.png',
  ];

  var index = Math.floor(Math.random() * avatars.length);

  return "/avatars/" + avatars[index];
}

Number.prototype.toPercent = function(){
return (Math.round(this * 10000)/100).toFixed(2) + '%';
}